package com.example.myapplication.ui;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Contacts;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.example.myapplication.R;
import com.example.myapplication.tools.ComSendFileToHttpDialog;
import com.example.myapplication.tools.ToastUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PhotoChoose extends Activity {

    private final int CHOOSE_COM_IMAGE = 10;
    private final int PHOTO_CHOOSE = 12;

    String choosePath = "";
    ImageView image;
    String basePath = Environment.getExternalStorageDirectory().getPath() + "/haomo/";
    Context context;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_choose);

        context = this;
        image = findViewById(R.id.imageView);
    }

    //拍照
    public void TakePhoto(View view) {
        try {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            String fileName = "temp.jpg";// 照片命名
            String tagetPath = basePath+"photo/";
            File tagetFile = new File(tagetPath);
            if (!tagetFile.exists()) {
                tagetFile.mkdirs();
            }
            tagetFile = new File(tagetPath, fileName);
            String imageFilePath = tagetPath + fileName;// 该照片的绝对路径
//            Uri uri = Uri.fromFile(tagetFile);
//            Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileProvider",tagetFile);
            Uri uri;
            if (Build.VERSION.SDK_INT >= 24) {
                uri = FileProvider.getUriForFile(context.getApplicationContext(), "com.example.myapplication.fileprovider", tagetFile);
            } else {
                uri = Uri.fromFile(tagetFile);
            }
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            cameraIntent.putExtra("FilePath", imageFilePath);
            startActivityForResult(cameraIntent, CHOOSE_COM_IMAGE);
        } catch (Exception ex) {
            ex.printStackTrace();
            Toast.makeText(this, "不支持拍照", Toast.LENGTH_SHORT).show();
        }
    }

    // 选择图像
    public void SelectPhoto(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK, Contacts.People.CONTENT_URI);

        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 240);
        intent.putExtra("outputY", 240);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
        String newPath= basePath + "photo/" + sdf.format(new Date()) + ".jpg";
        choosePath = newPath;
        startActivityForResult(intent, PHOTO_CHOOSE);
    }

    private void setImage(){
        File f = new File("地址");
        if (f.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
            image.setImageBitmap(bitmap);
        }else{
            ToastUtils.showMessages("找不到图片",this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            switch (requestCode){
                case CHOOSE_COM_IMAGE:{
                    File f = new File(basePath + "photo/temp.jpg");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
                    String newPath= basePath + "photo/" + sdf.format(new Date()) + ".jpg";
                    File f2 = new File(newPath);
                    if(!f2.getParentFile().exists()){
                        f2.getParentFile().mkdirs();
                    }
                    choosePath = newPath;
                    boolean isRename = f.renameTo(f2);
                    if(isRename){
                        choosePath = newPath;
                        Bitmap bitmap = getBitmapFromUrl(choosePath,1000);
                        image.setImageBitmap(bitmap);
                        if(bitmap != null){
                            try {
                                saveBitmapToJPG(bitmap,f2);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }else{
                        ToastUtils.showMessages("拍照错误",context);
                    }
                    }
                    break;
                case PHOTO_CHOOSE:
                    Bitmap bitmap = data.getParcelableExtra("data");
                    File fc = new File(choosePath);
                    if(bitmap != null){

                        File parent = fc.getParentFile();
                        if(!parent.exists()){
                            parent.mkdirs();
                        }
                        image.setImageBitmap(bitmap);
                        FileOutputStream foutput = null;
                        try {
                            foutput = new FileOutputStream(fc);
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, foutput);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }finally{
                            if(null != foutput){
                                try {
                                    foutput.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }else if(fc.exists()){
                        bitmap = BitmapFactory.decodeFile(choosePath);
                        image.setImageBitmap(bitmap);
                    }else{
                        System.out.println("comInfo.class → onActivityResult → PHOTO_CHOOSE");
                    }
                    break;
            }
        }else if(requestCode == CHOOSE_COM_IMAGE && resultCode == RESULT_CANCELED){

        }
    }

    /**
     * 上传文件
     */
    private void upFile (String filePath){
        Handler handlerReceive = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        ToastUtils.showMessages("上传图片成功", context);
                        break;
                    case 1:
                        ToastUtils.showMessages("上传图片失败，请重试", context);
                        break;
                }

            };
        };
        ComSendFileToHttpDialog dl = new ComSendFileToHttpDialog(this, handlerReceive, "",filePath);
        dl.show();
    }

    /**
     * bitmap文件转bitmap并压缩
     * @param url 文件地址
     * @param scale 压缩后最大宽度或高度
     * @return
     */
    private Bitmap getBitmapFromUrl(String url, double scale) {

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 设置了此属性一定要记得将值设置为false
        Bitmap bitmap = BitmapFactory.decodeFile(url);
        // 防止OOM发生
        options.inJustDecodeBounds = false;
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleSize = 1;
        // 按照固定宽高进行缩放
        if(mWidth <= mHeight) {
            scaleSize = (float) (scale/mHeight);
        } else {
            scaleSize = (float) (scale/mWidth);
        }
        // 按照固定大小对图片进行缩放
        matrix.postScale(scaleSize, scaleSize);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true);
        // 用完了记得回收
        bitmap.recycle();
        return newBitmap;
    }

    //bitmap转文件
    public static void saveBitmapToJPG(Bitmap bitmap, File file) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(file);
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        stream.close();
    }
}
